package com.example.hao.retrofit;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;


import com.example.hao.retrofit.pojo.User;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
private static final String TAG = "Hao";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        test1();
        test2();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.3.100:8080/home/")
            //指定转换流
            .addConverterFactory(GsonConverterFactory.create()).build();
    /**
     * Retrofit 实现Get 请求
     */
    private void test1(){

        IUserRequest iUserRequest = retrofit.create(IUserRequest.class);//动态代理

        //创建请求处理程序
        Call<ResultData> register = iUserRequest.register("kim", "001");
        //异步发送请求
        register.enqueue(new Callback<ResultData>() {
            @Override
            public void onResponse(@NonNull Call<ResultData> call, @NonNull Response<ResultData> response) {
                ResultData body = response.body();

                String text = body != null ? body.toString() : null;
                Log.d(TAG, "onResponse: "+text);
                Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(@NonNull Call<ResultData> call, @NonNull Throwable t) {
                String message = t.getMessage();
                Log.e(TAG, "onFailure: "+message);
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void test2(){

        IUserRequest iUserRequest = retrofit.create(IUserRequest.class);

        Call<ResultData<User>> getUser = iUserRequest.getUser("Number");

        getUser.enqueue(new Callback<ResultData<User>>() {
            @Override
            public void onResponse(@NonNull Call<ResultData<User>> call, @NonNull Response<ResultData<User>> response) {
                ResultData<User> body = response.body();
                String text = body != null ? body.toString() : null;
                Log.d(TAG, "onResponse: "+text);

                Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(@NonNull Call<ResultData<User>> call, @NonNull Throwable t) {
                Log.e(TAG, "onFailure: "+t.getMessage() );
            }
        });
    }
}
